<template>
  <div class="page-register">
    <div class="header-wrapper">
      <article class="header">
        <a 
          href="/" 
          class="site-logo" 
        />
        <span class="login">
          <em class="bold">已有美团账户？</em>
          <a href="/login">
            <el-button 
              type="primary"
              size="small"
            >登录</el-button>
          </a>
        </span>
      </article>
    </div>
    <section>
      <el-form 
        ref="ruleForm"  
        :model="ruleForm"
        :rules="rules" 
        label-width="100px" 
        class="demo-ruleForm"
      >
        <!-- 昵称 -->
        <el-form-item 
          label="昵称" 
          prop="name"
        >
          <el-input v-model="ruleForm.name" />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item 
          label="邮箱" 
          prop="email"
        >
          <el-input v-model="ruleForm.email" />
          <el-button 
            size="mini"
            round
            @click="sendMsg"
          >发送验证码</el-button>
          <span class="status">{{ statusMsg }}</span>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item 
          label="验证码" 
          prop="code"
        >
          <el-input 
            v-model="ruleForm.code" 
            max-length="4"
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item 
          label="密码" 
          prop="pwd"
        >
          <el-input 
            v-model="ruleForm.pwd" 
            type="password"
          />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item 
          label="确认密码" 
          prop="cpwd"
        >
          <el-input 
            v-model="ruleForm.cpwd" 
            type="password"
          />
        </el-form-item>

        <!-- 确认注册 -->
        <el-form-item>
          <el-button 
            type="primary"
            @click="register"
          >同意以下协议并注册</el-button>
          <div class="error">{{ error }}</div>
        </el-form-item>

        <!-- 协议 -->
        <el-form-item>
          <a 
            class="f1" 
            href="http://www.meituan.com/about/terms" 
            target="_blank"
          >《美团网用户协议》</a>
        </el-form-item>
      </el-form>
    </section>

    <footer class="footer--mini">
      <p class="copyright">
        ©<a 
          class="f1" 
          href="https://www.meituan.com"
        >meituan.com</a>&nbsp;<a 
          class="f1" 
          target="_blank" 
          href="http://www.miibeian.gov.cn/"
        >京ICP证070791号</a>&nbsp;<span class="f1">京公网安备11010502025545号</span>
      </p>
    </footer>
  </div>
</template>

<script>
import CryptoJS from 'crypto-js'
import { setTimeout } from 'timers';

export default {
  layout: "blank",
  data() {
    return {
      statusMsg: '',
      error: '',
      timerid: null,
      ruleForm: {
        name: '',
        code: '',
        pwd: '',
        cpwd: '',
        mail: ''
      },
      rules: {
        name: [
          { required: true, type: 'string', message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, type: 'email', message: '请输入邮箱', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '创建密码', trigger: 'blur' }
        ],
        cpwd: [
          { required: true, message: '确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请在此输入密码'))
              } else if (value !== this.ruleForm.pwd) {
                callback(new Error('两次输入密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    sendMsg() {
      let namePass
      let emailPass

      if (this.timerid) {
        return false
      }

      // 验证名称  有值则错误
      this.$refs['ruleForm'].validateField('name', valid => {
        namePass = valid
      })

      this.statusMsg = ''

      if (namePass) { // 验证不通过
        return false
      }

      // 验证邮箱
      this.$refs['ruleForm'].validateField('email', valid => {
        emailPass = valid
      })

      if (!namePass && !emailPass) {
        this.$axios.post('/users/verify', {
          username: encodeURIComponent(this.ruleForm.name),
          email: this.ruleForm.email
        })
          .then(({status, data}) => {
            if (status === 200 && data && data.code === 0) {
              let count = 60

              this.statusMsg = `验证码已发送，剩余${count--}秒`
              this.timerid = setInterval(() => {
                this.statusMsg = `验证码已发送，剩余${count--}秒`
                if (count === -1) {
                  this.statusMsg = '验证码已失效，请重新发送'
                  clearInterval(this.timerid)
                }
              }, 1000)
            } else {
              this.statusMsg = data.msg
            }
          })
      }
    },
    register() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.$axios.post('/users/signup', {
            username: window.encodeURIComponent(this.ruleForm.name),
            password: CryptoJS.MD5(this.ruleForm.pwd).toString(),
            email: this.ruleForm.email,
            code: this.ruleForm.code
          })
            .then(({status, data}) => {
              if (status === 200) {
                if (data && data.code === 0) {
                  location.href = '/login'
                } else {
                  this.error = data.msg
                }
              } else {
                this.error = `服务器出错，错误码：${status}`
              }

              setTimeout(() => {
                this.error = ''
              }, 1500)
            })
        }
      })
    }
  }
};
</script>

<style lang="stylus" scoped>
.header-wrapper
  min-width 980px
  color #666666
  border-bottom 2px solid #2bb8aa

.header
  margin 0 auto
  padding 10px 0
  width 980px

  .site-logo
    display inline-block
    width 54px
    height 36px
    text-indent -9999px
    background-position -669px -748px
    background-image url('//s0.meituan.net/bs/file/?f=fe-sso-fs:build/assets/sp-normal.2ee5c09.png')
  .login 
    float right

    .el-button
      background-color #2bb8aa

  .bold
    font-style normal

section
  margin 0 auto 30px
  padding-top 30px
  width 980px
  min-height: 300px
  padding-right 550px
  box-sizing border-box

  .status
    margin-left 20px
    color #e6a23c
    font-size 12px

  .error 
    color red

  .f1
    color #2bb8aa
    font-size 13px
.footer--mini
  padding-top 20px
  border-top 1px solid #eee
  text-align center
  font-size 12px
  color #999999
  a
    color #999999
    &:hover
      color #31bbac
</style>